

module ltc(
	input clk,    //120MHz 
	input rst_n,

	//output reg cnv, //触发芯片采样的信
	input busy,
	output reg scki,
	output reg sdi,
	input scko,
	input sdo0,

	output done
);

//同步busy信号
reg busy_diff1,busy_diff2;
wire busy_n;
assign busy_n = ~busy_diff1 & busy_diff2;
always@(posedge clk )
begin
	if(!rst_n)begin
		busy_diff1 <= 1'b0;
		busy_diff2 <= 1'b0; 
	end
	else begin
		busy_diff1 <= busy;
		busy_diff2 <= busy_diff1;
	end
end

//发送数据到ltc芯片的FSM  使用格雷码
localparam S_IDEL = 2'b00;
localparam S_SEND_1 = 2'b01;
localparam S_SEND_2 = 2'b11;
localparam S_DONE = 2'b10;

assign done = (cst==S_IDEL) ? 1'b1 : 1'b0 ;
reg [1 :0 ] cst ,nst;
reg [4:0]scnt;

//状态转移
always@(posedge clk)
begin
	if(!rst_n)begin
		cst <= S_IDEL ;
	end
	else begin
		cst <= nst;
	end
end

//状态转移判断
always@(*)
begin
	nst = S_IDEL;
	case(cst)
		S_IDEL:begin
			nst = busy_n ? S_SEND_1 : S_IDEL;
		end
		S_SEND_1:begin
			nst =  (scnt < 32'd24 ) ? S_SEND_2 : S_DONE;
		end
		S_SEND_2:begin
			nst =  (scnt < 32'd24 ) ? S_SEND_1 : S_DONE;
		end
		S_DONE:begin
			nst = S_IDEL;
		end
		default : nst = S_IDEL ; 
	endcase
end
//输出

reg [23:0] send_data;
always@(posedge clk)
begin
	if(!rst_n)begin
		sdi <= 0;
		scki <= 1;
		scnt <= 0;
		send_data <= 24'hf0ff0f;
	end
	else begin
		if( nst == S_IDEL)begin
			sdi <= 0;
			scki <= 1; 
			scnt <= 0;
			send_data <= 24'hf0ff0f;
		end
		else if( nst == S_SEND_1 )begin
			if( scnt < 32'd24 )begin
				scki <= 1'b0;
				sdi <= send_data[23];
				send_data <= send_data << 1;
			end
			else begin
				scki <= 1'b0;
				sdi <= 1'b0;
			end
		end
		else if( nst == S_SEND_2 )begin
			if(scnt < 32'd24 )begin
				scki <= 1'b1;
				scnt <= scnt + 1;
			end
			else begin
				scki <= 1'b0;
			end
		end
		else begin
			scki <= 1'b1;
			sdi <= 1'b0;
		end
	end
end


endmodule 

